//
//  LSPersonalDataVController.m
//  LookScore
//
//  Created by wr on 2017/12/16.
//  Copyright © 2017年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSPersonalDataVController.h"
#import "LSPersonalDataCell.h"
#import "LSSetNickNameVController.h"//设置或修改昵称
#import "LSRevampPasswardVController.h"//修改密码
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>
#import "TZImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "LSAccountArchive.h"
#import "LSHttpEnclosureTool.h"
#import "MBProgressHUD+MJ.h"
#import "LSPhoneResetVController.h"
#import <UIButton+WebCache.h>
@interface LSPersonalDataVController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(strong,nonatomic)UITableView *tableView;

@property(strong,nonatomic)NSArray *titleArray;


@end

@implementation LSPersonalDataVController
//{
//    BOOL isAccredit;
//}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor =LSBackGroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.title=@"个人资料";
    self.view.backgroundColor=LSBackGroundColor;
    
//    self.titleArray=@[@[@"头像",@"UID",@"昵称",@"修改密码"],@[@"手机号",@"微信号",@"QQ号"]];
    self.titleArray=@[@[@"头像",@"UID",@"昵称",@"修改密码"],@[@"手机号"]];
    [self.view addSubview:self.tableView];
    
    self.tableView.sd_layout.leftEqualToView(self.view).topEqualToView(self.view).rightEqualToView(self.view).bottomEqualToView(self.view);
}
#pragma mark 🔥 tableViewDelegate tableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSArray *array=self.titleArray[section];
    
    return array.count;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return LSControlHeight;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.width,10)];
    return backView;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section!=0) {
        return 10;
    }
    return 0;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LSPersonalDataCell *cell=[LSPersonalDataCell PersonalDataCellByTableView:tableView];
    NSArray *array=self.titleArray[indexPath.section];
    cell.titleLab.text=array[indexPath.row];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            cell.cellIndex=indexPath.row;
//            [cell.detailBu sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?=%@",[LSAccountArchive account].UserHeadUrl,[CommonClass readStampTimeString]]] forState:UIControlStateNormal completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//
//                if (!image) {
//                    image=[UIImage imageNamed:@"MineDefaultHead"];
//                }
//                image=[CommonClass clipImage:image scaleToSize:CGSizeMake(100, 100)];
//
////                [cell.detailBu setImage:image forState:UIControlStateNormal];
//            }];
            
            [cell.detailBu sd_setImageWithURL:[NSURL URLWithString:[LSAccountArchive account].UserHeadUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"MineDefaultHead"] options:SDWebImageRefreshCached];
        }else if (indexPath.row == 1){
            [cell.detailBu setTitle:[LSAccountArchive account].Cid forState:UIControlStateNormal];
            cell.rightImgBu.hidden = YES;
        }
        else if (indexPath.row == 2){
            [cell.detailBu setTitle:[LSAccountArchive account].DisplayName forState:UIControlStateNormal];
            if ([LSAccountArchive account].ModifyDisplayNameCount <= 0) {
                cell.rightImgBu.hidden = YES;
            }else{
                cell.rightImgBu.hidden = NO;
            }
            
        }else if (indexPath.row == 3){
            
            
            
        }
    }if (indexPath.section==1) {
        [cell.detailBu setTitle:[LSAccountArchive account].Mobile forState:UIControlStateNormal];
        if ([LSAccountArchive account].ModifyMobileCount <= 0) {
            cell.rightImgBu.hidden = YES;
        }else{
            cell.rightImgBu.hidden = NO;
        }
    }
    
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section==0) {
        if (indexPath.row==0) {
              [self startUpdateUserHeadImageRG];
        }else if (indexPath.row==1){
           
        }else if (indexPath.row==2){
//            只有一次修改机会 要加判断
            LSSetNickNameVController *nickNameVC=[[LSSetNickNameVController alloc]init];
            nickNameVC.cid=[LSAccountArchive account].Cid;
            if ([LSAccountArchive account].ModifyDisplayNameCount <= 0) {
                [MBProgressHUD showOnlyMessage:@"修改昵称次数已用完" afterDelay:1.5f];
            }
            else{
                if ([LSAccountArchive account].ModifyDisplayNameCount == 2) {
                    nickNameVC.type=KRevampOrSetNickNameIsSetting;
                }else{
                    nickNameVC.type=KRevampOrSetNickNameIsRevamp;
                }
                
//                if ([CommonClass isBlankString:[LSAccountArchive account].DisplayName]) {
//                    nickNameVC.type=KRevampOrSetNickNameIsSetting;
//                }else{
//                    nickNameVC.type=KRevampOrSetNickNameIsRevamp;
//                }
                [self.navigationController pushViewController:nickNameVC animated:YES];
                nickNameVC.PersonalDataChangedBlock = ^{
                    [self.tableView reloadData];
                    if (self.PersonalDataChangedBlock) {
                        self.PersonalDataChangedBlock();
                    }
                };
                
            }
            
            
        }else if (indexPath.row==3){
            LSRevampPasswardVController *passwardVC=[[LSRevampPasswardVController alloc]init];
            [self.navigationController pushViewController:passwardVC animated:YES];
            
        }
    }else if (indexPath.section==1){
        if (indexPath.row==0) {
            
            if ([LSAccountArchive account].ModifyMobileCount <= 0) {
                [MBProgressHUD showOnlyMessage:@"修改手机号次数已用完" afterDelay:1.5f];

            }else{
                LSPhoneResetVController *phoneResetVC=[[LSPhoneResetVController alloc]init];
                [self.navigationController pushViewController:phoneResetVC animated:YES];
                phoneResetVC.PersonalDataChangedBlock = ^{
                    [self.tableView reloadData];
                    if (self.PersonalDataChangedBlock) {
                        self.PersonalDataChangedBlock();
                    }
                };
                
            }
        }else if (indexPath.row==1){
            
        }else if (indexPath.row==2){
            
        }
    }
    
    
}



#pragma mark 🔥 替换头像
-(void)startUpdateUserHeadImageRG{
    
//    KWeakSelf(self);
    UIActionSheet *sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    sheet.tag = 898989;
    [sheet showInView:self.view];
  
}
#pragma mark 选中拍照或者相册选择
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    
    if (buttonIndex < 2) {
        if (actionSheet.tag == 898989) {
            
            [self actionSheetDidClickedButtonAtIndex:buttonIndex];
            
        }else if (actionSheet.tag == 8989890){
            
            if (buttonIndex == 0) {
//                [self ALAuthorizationStatusButtonIndex:buttonIndex];
                [self openJurisdiction];
            }else{
                return;
            }
            
        }
    }
    else{
        return;
    }
 
}



-(void)actionSheetDidClickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {//相机
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
            // 无权限 引导去开启
            [self ALAuthorizationStatusButtonIndex:buttonIndex];
        }else{
            [self selectImageFormGalleryOrGalleryIndex:buttonIndex];
        }
    }else if (buttonIndex==1){//相册
        
        
        
//        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){
            // 无权限 做一个友好的提示
            [self ALAuthorizationStatusButtonIndex:buttonIndex];
        }
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                MyLog(@"Authorized");
                [self selectImageFormGalleryOrGalleryIndex:buttonIndex];
            }else{
                MyLog(@"Denied or Restricted");
            }
        }];
        

    }else{
        return;//取消按钮
    }
    
}


-(void)openJurisdiction{
    NSURL *url=[NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication]canOpenURL:url]) {
        [[UIApplication sharedApplication]openURL:url];
    }
}
-(void)ALAuthorizationStatusButtonIndex:(NSInteger)buttonIndex{
    
    //    __block NSInteger tempIndex=buttonIndex;
    
    //    NSString *message=tempIndex==0?@"相机访问受限,需前往授权后才能使用":@"相册访问受限,需前往授权后才能使用";
//    dispatch_async(dispatch_get_main_queue(), ^{
        UIActionSheet *sheet  = [[UIActionSheet alloc] initWithTitle:@"访问受限" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"前往授权", nil];
        sheet.tag = 8989890;
        [sheet showInView:self.view];
//    });
    
    
    
}


/*
 #pragma mark - LCActionSheet 代理方法
 - (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
 if (buttonIndex==2) {
 return;//取消按钮
 }
 [self selectImageFormGalleryOrGalleryIndex:buttonIndex];
 
 }*/


#pragma mark - UIImagePickerControllerDelegate
-(void)selectImageFormGalleryOrGalleryIndex:(NSInteger)selectIndex{
    
    UIImagePickerController *imagePickerController=[[UIImagePickerController alloc]init];
    imagePickerController.delegate=self;
    imagePickerController.allowsEditing=YES;
    if (selectIndex==0) {
        imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
    }else if(selectIndex==1){
        imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary] ){
        
        [imagePickerController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : LSNavTitlenColor}];
        imagePickerController.navigationBar.translucent = NO;//导航栏设置为不透明的
        [imagePickerController.navigationBar setTintColor:LSTitleWhiteColor];
        [imagePickerController.navigationBar setBarTintColor:LSNavMainColor];
    }
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        imagePickerController.allowsEditing=YES;
        if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
            self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
    }
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *image=[self OriginImage:info[UIImagePickerControllerEditedImage] scaleToSize:CGSizeMake(200, 200)];
    NSArray *array=@[image];

    MyLog(@"image --- %@",array);
    [picker dismissViewControllerAnimated:YES completion:^{
        
        NSDictionary *parameters=@{@"type":@"0"};
        
        [LSHttpEnclosureTool Upload:LSUSERUPLOADIMG parameters:parameters uploadParamArray:array resBlock:^(id responseObject) {
            if (responseObject) {
                MyLog(@"postImage --- %@",responseObject);
                NSString *urlString=(NSString *)responseObject;
//                [LSAccountArchive account].UserHeadUrl=@"";
//                [self.tableView reloadData];
                NSDictionary *headImgDic=@{@"cid":[LSAccountArchive account].Cid,@"headUrl":urlString};
                
                [LSHttpEnclosureTool POST:LSUSERCHANGEHEAD parameters:headImgDic resBlock:^(id responseObject) {
                    if (responseObject) {
                        //http://101.132.148.59:306/userHead/851a5847ca574972b52ab9c85fac6ad3.jpg?t=1528703186
                        MyLog(@"changHead --- %@",responseObject);
                        NSString *userImgString=(NSString *)responseObject;
                        
                        LSAccountCoder *coderModel = [LSAccountArchive account];
                        coderModel.UserHeadUrl=userImgString;
                        [LSAccountArchive saveAccount:coderModel];
                        [self.tableView reloadData];
                        [notifiCenter postNotificationName:@"LOADCIRCLEDATA" object:nil];
                        if (self.PersonalDataChangedBlock) {
                            self.PersonalDataChangedBlock();
                        }
                    }
                }];
            }
        }];
    
    }];
    
}




- (UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
    CGSize newSize;
    if (image.size.height / image.size.width > 1){
        newSize.height = size.height;
        newSize.width = size.height / image.size.height * image.size.width;
    } else if (image.size.height / image.size.width < 1){
        newSize.height = size.width / image.size.width * image.size.height;
        newSize.width = size.width;
    } else {
        newSize = size;
    }
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContextWithOptions(newSize, YES, 0);
    
//    [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0,newSize.width, newSize.height) cornerRadius:newSize.width] addClip];
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
